<?php

if ( !defined( 'CMS_ROOT' ) )
	die;

class RegUsers {

	public static $verification_url = 'user/verification';
	public static $login_url = 'user/login';
	public static $login_error_url = 'user/login-error';
	public static $registration_url = 'user/registration';
	public static $forgot_password_url = 'user/forgot-password';
	public static $logout_url = 'user/logout';
	public static $verification_length = 10;
	public static $new_pass_length = 5;
	public static $user_permissions = 'reg_user';
	public static $temp_user;
	public static $user_extend_data;

	public static function registration_url()
	{
		return get_url( self::$registration_url );
	}

	public static function login_url()
	{
		return get_url( self::$login_url );
	}

	public static function login_error_url()
	{
		return get_url( self::$login_error_url );
	}

	public static function logout_url()
	{
		return get_url( self::$logout_url );
	}

	public static function verification_url()
	{
		return get_url( self::$verification_url );
	}

	public static function forgot_password_url()
	{
		return get_url( self::$forgot_password_url );
	}

	public static function registration()
	{
		if ( get_request_method() == 'POST' || get_request_method() == 'AJAX' )
		{
			$errors = array();

			$result_extend = self::process_extend_data();
			if ( $result_extend !== true )
			{
				$errors = $result_extend;
			}

			$data = $_POST['user'];
			$data['username'] = htmlspecialchars( $data['username'], ENT_QUOTES );
			$data['email'] = htmlspecialchars( $data['email'], ENT_QUOTES );

			if ( strlen( $data['password'] ) >= 5 && $data['password'] == $data['confirm'] )
			{
				$data['password'] = sha1( $data['password'] );
				unset( $data['confirm'] );
			}
			else
			{
				$errors[] = __( 'Password and Confirm are not the same or too small!' );
			}

			if ( strlen( $data['username'] ) < 3 )
				$errors[] = __( 'Username must contain a minimum of 3 characters!' );

			if ( strlen( $data['email'] ) < 5 )
				$errors[] = __( 'Введите E-mail' );

			$temp_user_already_exists = Record::findOneFrom( 'TempUser', 'username = ? OR email =?', array($data['username'], $data['email']) );
			$user_already_exists = Record::findOneFrom( 'User', 'username = ? OR email =?', array($data['username'], $data['email']) );
			if ( $temp_user_already_exists != false || $user_already_exists != false )
			{
				$errors[] = __( 'Такой пользователь уже зарегистрирован' );
			}



			$user = new TempUser( $data );
			if ( !empty( $errors ) )
			{
				self::displayErrors( $errors );
				echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/registration', array('user' => $user) );
				return false;
			}

			$user->rand_key = self::randomString( self::$verification_length );

			if ( $user->save() )
			{
				Observer::notify( 'user_after_registration', array($user, self::$user_extend_data) );

				self::$temp_user = $user;
				if ( self::sendKey() )
				{
					echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/verification', array('user' => $user) );
				}
				return true;
			}
		}
		else
		{
			$user = new TempUser();
			echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/registration', array('user' => $user) );
		}
	}

	public static function verification()
	{
		$id = (int) $_GET['id'];
		$key = htmlspecialchars( $_GET['key'], ENT_QUOTES );
		$errors = array();

		if ( empty( $id ) || empty( $key ) )
		{
			$errors = __( 'Перейдите по ссылке из отправленного вам письма.' );
			return self::displayErrors( $errors );
		}

		$temp_user = Record::findByIdFrom( 'TempUser', $id );

		if ( $temp_user && $temp_user->rand_key == $key )
		{
			if ( $temp_user->delete() )
			{
				unset( $temp_user->rand_key );
				$user = new User( );

				$user->name = $temp_user->name;
				$user->email = $temp_user->email;
				$user->password = $temp_user->password;
				$user->username = $temp_user->username;
				$user->language = $temp_user->language;
				$user->created_on = $temp_user->created_on;
				$user->updated_on = $temp_user->updated_on;
				$user->created_by_id = $temp_user->created_by_id;
				$user->updated_by_id = $temp_user->updated_by_id;

				if ( $user->save() )
				{
					Observer::notify( 'user_after_verification', array($user) );
					self::setPermissions( $user->id );
					//UserPermission::setPermissionsFor( $user->id, self::$user_permissions );
					echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/verification_success' );
					return true;
				}
			}
		}
		else
		{
			$errors[] = 'Возникла ошибка';
		}

		if ( !empty( $errors ) )
		{
			self::displayErrors( $errors );
			return false;
		}
	}

	private static function setPermissions( $user_id )
	{
		$tablename = Record::tableNameFromClassName( 'UserPermission' );

		// remove all perms of this user
		$sql = 'DELETE FROM ' . $tablename . ' WHERE user_id=' . (int) $user_id;
		Record::$__CONN__->exec( $sql );

		// add the new perms
		$perms = Record::findOneFrom( 'Permission', 'name=?', array(self::$user_permissions) );

		$sql = 'INSERT INTO ' . $tablename . ' (user_id, permission_id) VALUES (' . (int) $user_id . ',' . (int) $perms->id . ')';
		Record::$__CONN__->exec( $sql );
	}

	public static function login()
	{
		if ( get_request_method() == 'POST' || get_request_method() == 'AJAX' )
		{
			if ( AuthUser::isLoggedIn() )
			{
				$errors = array('Вы уже вошли на сайт.');
				self::displayErrors( $errors );
				return true;
			}

			$data = isset( $_POST['login'] ) ? $_POST['login'] : array('username' => '', 'password' => '');

			if ( AuthUser::login( $data['username'], $data['password'], isset( $data['remember'] ) ) )
			{
				$redirect = CMS_URL;

				if ( isset( $_SERVER['HTTP_REFERER'] ) && !empty( $_SERVER['HTTP_REFERER'] ) )
				{
					$redirect = $_SERVER['HTTP_REFERER'];
				}
				redirect( $redirect );
			}
			else
			{
				redirect( self::login_error_url() );
			}
		}
		else
		{
			if ( AuthUser::isLoggedIn() )
			{
				$errors = array('Вы уже вошли на сайт.');
				self::displayErrors( $errors );
				return true;
			}
			else
				echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/login' );
		}
	}

	public static function login_error()
	{
		$errors = array('Вы ввели неправильный E-mail или пароль.');
		self::displayErrors( $errors );
		echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/login' );
	}

	public static function logout()
	{
		AuthUser::logout();

		$redirect = CMS_URL;

		if ( isset( $_SERVER['HTTP_REFERER'] ) && !empty( $_SERVER['HTTP_REFERER'] ) )
		{
			$redirect = $_SERVER['HTTP_REFERER'];
		}

		redirect( $redirect );
	}

	public static function forgotPassword()
	{
		if ( get_request_method() == 'POST' || get_request_method() == 'AJAX' )
		{
			$result = self::sendPasswordTo( $_POST['forgot']['email'] );
			if ( $result )
			{
				echo 'Пароль отправлен вам на E-mail';
				return;
			}
			else
			{
				$errors = array('Ошибка при отправке пароля.');
				self::displayErrors( $errors );
			}
		}

		echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/forgot_pass' );
	}

	private static function randomString( $len )
	{
		$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

		$str = '';
		for ( $i = 0; $i < $len; $i++ )
		{
			$str .= substr( $pool, mt_rand( 0, strlen( $pool ) - 1 ), 1 );
		}
		return $str;
	}

	private static function sendKey()
	{
		$link = self::verification_url() . '?id=' . self::$temp_user->id . '&key=' . self::$temp_user->rand_key;

		use_helper( 'Email' );
		$message = new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/verification_mail', array('user' => self::$temp_user, 'link' => $link) );
		$site_host = dirname( $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] );
		$email = new Email();
		$email->mailtype = 'html';
		$email->from( 'no-reply@' . $site_host, Setting::get( 'admin_title' ) );
		$email->to( self::$temp_user->email );
		$email->subject( __( 'Your verification link from :site_name', array(':site_name' => Setting::get( 'admin_title' )) ) );
		$email->message( $message );
		return $email->send();
	}

	private static function sendPasswordTo( $email )
	{
		$user = User::findBy( 'email', $email );

		if ( $user )
		{
			use_helper( 'Email' );

			$new_pass = self::randomString( self::$new_pass_length );
			$user->password = sha1( $new_pass );
			$user->save();

			$message = new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/forgot_pass_mail', array('user' => $user) );
			$site_host = dirname( $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] );
			$email = new Email();
			$email->mailtype = 'html';
			$email->from( 'no-reply@' . $site_host, Setting::get( 'admin_title' ) );
			$email->to( $user->email );
			$email->subject( __( 'Your new password from :site_name', array(':site_name' => Setting::get( 'admin_title' )) ) );
			$email->message( $message );

			return $email->send();
		}
	}

	private static function displayErrors( $errors )
	{
		if ( is_array( $errors ) && !empty( $errors ) )
		{
			echo new View( '../../' . PLUGINS_DIR_NAME . '/registered_users/views/errors', array('errors' => $errors) );
		}
	}

	private static function process_extend_data()
	{
		$data = $_POST['user_extend'];
		$errors = array();

		foreach ( $data as &$v )
		{
			if ( is_array( $v ) )
			{
				foreach ( $v as &$v2 )
				{
					$v2 = htmlspecialchars( $v2, ENT_QUOTES );
				}
			}
			else
			{
				$v = htmlspecialchars( $v, ENT_QUOTES );
			}
		}


		if ( strlen( $data['name']['last'] ) < 3 )
			$errors[] = 'Введите Фамилию';
		if ( strlen( $data['name']['first'] ) < 3 )
			$errors[] = 'Введите Имя';
		if ( strlen( $data['name']['second'] ) < 3 )
			$errors[] = 'Введите Отчество';
		if ( strlen( $data['phone'] ) < 3 )
			$errors[] = 'Введите контактный телефон';
		if ( strlen( $data['passport']['number'] ) < 8 )
			$errors[] = 'Введите серию и номер паспорта';
		if ( strlen( $data['passport']['vidan'] ) < 8 )
			$errors[] = 'Введите кем выдан паспорт';
		if ( strlen( $data['address'] ) < 8 )
			$errors[] = 'Введите адрес';

		$_POST['user']['name'] = $data['name']['first'];
		$data['name'] = $data['name']['last'] . ' ' . $data['name']['first'] . ' ' . $data['name']['second'];
		$_POST['user']['username'] = $data['name'];

		$data['passport'] = $data['passport']['number'] . ' ' . $data['passport']['vidan'] . ' ' .
				$data['passport']['year'] . '-' . $data['passport']['month'] . '-' . $data['passport']['day'];
		$data['birthday'] = strtotime( $data['birthday']['year'] . '-' . $data['birthday']['month'] . '-' . $data['birthday']['day'] );
		$data['birthday'] = date( 'Y-m-d H:i:s', $data['birthday'] );

		$data['email'] = htmlspecialchars( $_POST['user']['email'], ENT_QUOTES );

		self::$user_extend_data = $data;

		if ( !empty( $errors ) )
			return $errors;
		else
			return true;
	}

}